<script setup lang="ts" name="App">
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { handleError } from './router'
import { getCurrentInstance } from 'vue'

const router = useRouter()
const app = getCurrentInstance()?.appContext.app

// 全局错误处理
onMounted(() => {
  // 捕获Vue应用中的错误
  if (app) {
    app.config.errorHandler = (err: unknown, _instance: any, info: string) => {
      console.error('Vue应用错误:', err, info)
      const errorMessage = err instanceof Error ? `${err.message}\n${info}` : `未知错误\n${info}`
      handleError(router, {
        message: errorMessage,
        type: 'error',
        stack: err instanceof Error ? err.stack : undefined
      })
    }
  }

  // 捕获未处理的Promise错误
  window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise错误:', event.reason)
    handleError(router, {
      message: event.reason?.message || 'Promise执行失败',
      type: 'error',
      stack: event.reason?.stack
    })
    event.preventDefault()
  })

  // 捕获全局JavaScript错误
  window.addEventListener('error', (event) => {
    // 首先检查event.error是否为null，如果是null则直接返回
    if (event.error === null) {
      return
    }

    console.error('全局JavaScript错误:', event.error)

    // 避免重复处理错误
    if (event.error?.alreadyHandled) return

    // 过滤掉特定的非致命错误
    const errorMessage = event.error?.message || event.message || ''
    const shouldIgnore =
      errorMessage.includes('ResizeObserver loop') || // 忽略ResizeObserver循环错误
      errorMessage.includes('Script error') || // 忽略跨域脚本错误
      !errorMessage // 忽略空错误消息

    if (shouldIgnore) {
      return
    }

    handleError(router, {
      message: errorMessage,
      type: 'error',
      stack: event.error?.stack
    })

    // 标记错误为已处理
    if (event.error) {
      event.error.alreadyHandled = true
    }
  })

  // 监听网络请求错误
  const originalFetch = window.fetch
  window.fetch = async (...args) => {
    try {
      const response = await originalFetch(...args)

      // 检查HTTP错误状态码
      if (!response.ok) {
        throw new Error(`网络请求失败: ${response.status} ${response.statusText}`)
      }

      return response
    } catch (error: any) {
      console.error('网络请求错误:', error)
      handleError(router, {
        message: error.message,
        type: 'network',
        code: String(error.status || 'NETWORK_ERROR')
      })
      throw error // 重新抛出错误，允许组件单独处理
    }
  }
})
</script>

<template>
  <div class="page">
    <router-view />
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 14px;
  line-height: 1.5;
  color: #303133;
  background-color: #f5f7fa;
  overflow-x: hidden;
  overflow-y: auto;
}

html::-webkit-scrollbar,
body::-webkit-scrollbar {
  display: none;
}

html,
body {
  scrollbar-width: none;
}

html,
body {
  -ms-overflow-style: none;
}

#app {
  height: 100%;
}

.page {
  height: 100%;
}
</style>

<style scoped>
.page {
  min-height: 100vh;
}
</style>
